const { decode } = require("jsonwebtoken");
const HttpException = require("../../exceptions/http_expetion");

module.exports.authMiddleware = async (req, res, next) => {
  const authHeader = req.headers.authorization;
  if (!authHeader) {
    return next(
      new HttpException(
        401,
        "authorization 必须提供",
        "authorization missing!!!"
      )
    );
  }

  //验证token类型
  const authHeaderArr = authHeader.split(" ");
  if (authHeaderArr[0] != "Token") {
    return next(
      new HttpException(401, "authorization 格式错误", "Token missing!!!")
    );
  }

  //验证token内容
  if (!authHeaderArr[1]) {
    return next(
      new HttpException(
        401,
        "authorization 格式错误",
        "Token Content missing!!!"
      )
    );
  }

  //解签验证
  try {
    const user = await decode(authHeaderArr[1]);
    if (!user) {
      return next(new HttpException(401, "Token 内容不存在", "token error!!!"));
    }
    req.user = user;
    req.token = authHeaderArr[1];
    return next();
  } catch (error) {
    return next(new HttpException(401, "Token验证失败", e.message));
  }
};
